#!/bin/bash
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2022-11-10 14:19:49
# @LastEditTime: 2023-12-06 15:48:09
# @Description:
###
# curl  -s http://wuyou.run/services/python3.sh |bash

# 判断是否为中国地区
is_china() {
    if [[ $(curl -sSL https://ipapi.co/country/) = "CN" ]]; then
        return 0
    else
        return 1
    fi
}

# 根据地区选择镜像源
select_country() {
    if is_china; then
        echo "检测在中国地区，将使用国内镜像源。"
        python_repository="https://repo.huaweicloud.com/python"
    else
        echo "检测不在中国地区，将使用官方镜像源。"
        python_repository="https://www.python.org/ftp/python"
    fi
}

# 定义要查询的网站列表以获取Python最新版本
websites=(
    "https://docs.python.org/3/"
    "https://python.p2hp.com/"
)

# 初始化最新版本号变量
latest_version=""

# 查询并设置最新版本号
for url in "${websites[@]}"; do
    response=$(curl -sL "$url")
    version=$(echo "$response" | grep -oP "Python [0-9]+\.[0-9]+\.[0-9]+" | head -n 1 | awk '{print $2}')
    if [ -n "$version" ]; then
        latest_version="$version"
        echo "查询:$url 版本号: $latest_version"
        break
    fi
done

# 检测并安装依赖
detect_and_install_deps() {
    if command -v apt &> /dev/null; then
        # Debian/Ubuntu系列
        apt update
        apt install -y python3-dev python3-ldap libldap2-dev \
            libffi-dev libxml2-dev libxslt-dev \
            zlib1g-dev libbz2-dev libexpat1-dev libreadline-dev \
            libjpeg-dev libpng-dev libtiff-dev libwebp-dev \
            libssl-dev python3-pip gcc
    elif command -v yum &> /dev/null; then
        # CentOS/RHEL系列
        yum install -y python3-devel python3-ldap openldap-devel \
            libffi-devel libxml2-devel libxslt-devel \
            bzip2-devel expat-devel readline-devel \
            libjpeg-devel libpng-devel libtiff-devel libwebp-devel \
            openssl-devel openssl11 openssl11-devel gcc
        
        export CFLAGS=$(pkg-config --cflags openssl11)
        export LDFLAGS=$(pkg-config --libs openssl11)
    else
        echo "无法识别系统包管理器，请手动安装依赖。"
        exit 1
    fi
}

# 主程序
if [ -d "/usr/local/python3" ]; then
    echo "检测到python3已安装"
else
    detect_and_install_deps

    if [ ! -f "Python-$latest_version.tar.xz" ]; then
        select_country
        wget -c "$python_repository/$latest_version/Python-$latest_version.tar.xz"
        if [ $? != 0 ]; then
            echo "下载失败 !!!"
            exit 1
        fi
    fi

    tar xf "Python-$latest_version.tar.xz"
    cd "Python-$latest_version"
    ./configure --prefix=/usr/local/python3
    make -j 2
    make install
    cd ..

    # 清理旧链接，创建新链接
    rm -f /usr/local/bin/python3 /usr/bin/python3 /usr/local/bin/pip3
    ln -s /usr/local/python3/bin/python3 /usr/local/bin/python3
    ln -s /usr/local/python3/bin/pip3 /usr/local/bin/pip3
fi

# 清理临时文件
rm -rf "Python-$latest_version" "__pycache__"